/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elektra;

import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

/**
 *
 * @author adee
 */
public class FacebookChat implements ChatManagerListener {
   
   private String apiKey="353574954653814";
   private String accessToken = "AAAFBkxWS2HYBAOB6lG5yXJwy4PhPZCBMoPgWhFDhvPWZAPfMwYbZAYv2oGtafyasqX4zZBczmtKKoeJykZCMnxgSfk08TNIv78r32257TAwZDZD";
   private ConnectionConfiguration config;
   private XMPPConnection  mFbConnection;
   private boolean connected;
   private ChatManager chatManager;
   private HashSet<Elektra> chatSet;
   private Thread chatTread;
   private FacebookChat self;
   private static final Logger LOG = Logger.getLogger(FacebookChat.class.getName());
   private MessageListener messageListener;
   public FacebookChat() {
          this.config = new ConnectionConfiguration("chat.facebook.com", 5222);
          this.config.setSASLAuthenticationEnabled(true);
          this.mFbConnection = new XMPPConnection(config);
          SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);
          SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
          this.chatSet = new HashSet<Elektra>();
          this.self = this;
          this.messageListener = messageListener;
    }
   
   public void connect(){ 
       this.chatTread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    mFbConnection.connect();
                    LOG.info("Connected to Facebook");
                    mFbConnection.login(apiKey, accessToken, "Application");
                    LOG.info("Logined as Elektra to Facebook");
                    chatManager = mFbConnection.getChatManager();
                    chatManager.addChatListener(self);
                    LOG.info("Waiting for incomeing chat");
                } catch (XMPPException ex) {
                    LOG.log(Level.SEVERE, "Logint to facebok failed", ex);
                }
                
            }
        });
    
         this.chatTread.run();
   }

    @Override
    public void chatCreated(Chat chat, boolean bln) {
       this.chatSet.add(new Elektra(chat));
       LOG.log(Level.INFO,"ChatCreated", chat);
       
    }
}
